﻿using System;
using System.Data.Entity;
using Domain.DbContext;
using IBll;
using System.Linq;
using Domain.Database;
using Common;
using CommonModel.Config;
using CommonModel.Constant;

namespace Bll
{
    /// <summary>
    /// 用户服务
    /// </summary>
    public class UserInfoBll:IUserInfoBll
    {
        public ModelContainer CurrentDbContext { get; set; }
        public ICacheBll CacheBll { get; set; }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="loginPassword"></param>
        /// <returns></returns>
        public bool Login(string loginName, string loginPassword)
        {
            bool result = false;

            UserInfo userinfo= CurrentDbContext.UserInfoes.FirstOrDefault(a=>a.LoginName==loginName.Trim()&&a.LoginPassword==loginPassword.Trim());
            //var linq = from a in CurrentDbContext.UserInfoes
            //           where a.LoginName == loginName && a.LoginPassword == loginPassword
            //           select a;
            if (userinfo != null)
            {
                #region 更新用户登录信息
                userinfo.LastLoginTime = DateTime.Now;
                userinfo.LastLoginIp = HttpHelper.GetClientIPAddress();
                CurrentDbContext.Entry(userinfo).State = EntityState.Modified;
                CurrentDbContext.SaveChanges();
                #endregion

                #region 加入用户信息到缓存
                string cookieValue = CacheIdentity.Login + "_" + StringHelper.GetGuidString();
                CookieHelper.SetCookie(CookieConfig.LoginCookieName, cookieValue);
                DateTime expireTime = DateTime.Now.AddMinutes(Double.Parse(CacheConfig.CommonCacheTime));
                CacheBll.Add(cookieValue, userinfo, expireTime);
                #endregion
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public bool Logout()
        {
            bool result = true;

            CacheBll.Remove(CookieHelper.GetCookieValue(CookieConfig.LoginCookieName));

            return result;
        }
    }
}
